package com.sjf.JavaNIO.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.StandardCharsets;

/**
 * @author <huangtang>
 * @since 2022/4/14 17:11
 **/
public class PipeDemo1 implements Runnable {

    public static void main ( String[] args ) throws IOException {
        //1 获取管道
        Pipe pipe = Pipe.open ();
        new Thread (() -> {
            //2 获取sink通道
            Pipe.SinkChannel sink = pipe.sink ();
            //3 创建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate (1024);
            byteBuffer.put ("hello,sjf".getBytes (StandardCharsets.UTF_8));
            byteBuffer.flip ();
            //4 写入数据
            try {
                sink.write (byteBuffer);
            } catch (Exception e) {
                e.printStackTrace ();
            }
        }).start ();

        new Thread (() -> {
            //5 获取source通道
            Pipe.SourceChannel source = pipe.source ();
            //6 创建缓冲区，读取数据
            ByteBuffer byteBuffer2 = ByteBuffer.allocate (1024);
            int length = 0;
            try {
                length = source.read (byteBuffer2);
                System.out.println (new String (byteBuffer2.array () , 0 , length));
            } catch (IOException e) {
                e.printStackTrace ();
            }
        }).start ();

    }

    @Override
    public void run () {

    }
}
